import { onKeyStroke } from '@vueuse/core';
import { nextTick } from 'vue';
import { deleteById } from '@/store/program/utils';
import {
  activeId,
  cloneList,
  currentFolder,
  deleteFolder,
  targetKey,
} from './bus';
import { selectedKey } from './main/data/bus';
import { notify } from './components/notify/bus';

export default {
  init() {
    onKeyStroke('F2', (e) => {
      e.preventDefault();
      if (targetKey.value === 'folderKey') {
        currentFolder.value.editMode = !currentFolder.value.editMode;
        nextTick(() => {
          const inputEl = document.getElementById(
            currentFolder.value.id
          ) as HTMLInputElement;
          if (!inputEl) {
            return;
          }
          inputEl.select();
          inputEl.onblur = () => {
            currentFolder.value.editMode = false;
          };
          inputEl.onkeydown = (ev: KeyboardEvent) => {
            if (ev.key === 'Enter') {
              currentFolder.value.editMode = false;
            }
          };
        });
      }
      if (targetKey.value === 'fileKey') {
        nextTick(() => {
          if (selectedKey.value.size === 1) {
            cloneList.value.forEach((m) => {
              if (Array.from(selectedKey.value)[0] === m.id) {
                m.editMode = true;
              }
            });
          }
        });
      }
    });
    onKeyStroke('Delete', () => {
      if (targetKey.value === 'folderKey') {
        deleteFolder(currentFolder.value.id);
      } else if (targetKey.value === 'fileKey') {
        const ids = Array.from(selectedKey.value);
        notify({
          msg: `将会删除${ids.length}个文件`,
          title: '警告',
          onComfirm() {
            ids.forEach((v) => {
              currentFolder.value.children =
                currentFolder.value.children?.filter((m) => {
                  return m.id !== v;
                });
            });
          },
        });
      }
    });
  },
};
